<?php
class EventsController extends EventsAppController {

	var $name = 'Events';
	var $components = array('Auth','Session','RequestHandler','Email');
	var $helpers = array('Form','Html','Cms.Index','Events.EventForm');//,'Users.UserContent','Modules.Section','Rating.rating', 'Time', 'Votes.Vote','CustomFieldDisplay'
	var $msgDate = null;
	protected $autoAdminActions = array('admin_bulkDelete','admin_bulkPublish','admin_bulkUnpublish');

	function beforeFilter()
	{
		$this->Auth->allow('index','view','populartw','otherpopular','recentevents','upcomingevents','whosin','seeByDate','browse','generate_cal_file','suggestListings','newsletter');
		$this->Auth->loginAction = array("plugin"=>"users","controller"=>"users",'action'=>'login');
		//$this->helpers[] = "GeoMap";
		parent::beforeFilter();
	}

	function populartw() 
	{
		$this->Event->setScope('published');
		//$this->pageTitle = __('Popular events this week');
		//$order = array("(Event.soundscool_count + Event.whosin_count)" => "DESC");
		$order = array("Event.interested_count" => "DESC");
		$view_type = 'table_view';
		$conditions = $this->Event->getSeeByDateCondition("This_Week", date('Y-m-d'));
		
		$populartwevents = $this->Event->find("all", array('conditions'=>$conditions,'recursive'=>0, 'order'=>$order));
		if(isset($this->params['requested'])) 
		{
             return array($populartwevents,$view_type);
        }
		$this->set('view_type', $view_type);
		$this->set('eventData', $populartwevents);
		$this->set('loggedInUserId',$this->Session->read('Auth.User.id'));
		$this->set('eventCallerName','populartw');
		$this->render('browse');
	}

	function seeByDate($viewBy = null) 
	{
		if ($viewBy)
		{
			/*if(!isset($this->params['requested']) || $this->params['requested'] != true)
			{
				$this->actionId = 'browseEvents';
			}
			*/
			$this->Event->setScope('published');
			$order = array("Event.title" => "DESC");
			$view_type = 'blog_view';
			//$this->pageTitle = __('Browse events for: ' . str_replace("_"," ",$viewBy));
			$this->set('myTitle', sprintf(__('Browse Events For: %s', true), __(str_replace("_"," ",$viewBy))));
			
			$conditions = $this->Event->getSeeByDateCondition($viewBy);
			
			$seeByDateEvents = $this->Event->find("all", array('conditions'=>$conditions,'recursive' => 0,'order' => $order));
			if(isset($this->params['requested'])) 
			{
				 return array($seeByDateEvents,$view_type);
			} 
			
			$this->set('view_type', $view_type);
			$this->set('eventData', $seeByDateEvents);
			$this->set('loggedInUserId',$this->Session->read('Auth.User.id'));
			$this->set('eventCallerName','seebydate');
			$this->render('browse');
		}
		else
		{
			$this->redirect(array('plugin'=>'events','controller'=>'events','action'=>'index'));
		}
	}

	function browse() 
	{
		$defaultOptions = array(
				'ByTime'=>'All',
				'SortBy'=>'Most_Popular',
				'ByCategory'=>'A'
		);
		$viewBy = null;
		$viewByValue = null;
		$isChecked = null;
		$browseParams = array();
		
		if ($this->Session->check('eventBrowseParams'))
		{
			$browseParams = $this->Session->read('eventBrowseParams');
		}
		
		if(count($this->params['named'])>0)
		{
			if(isset($this->params['named']['ByTime'])) 
			{
				$viewBy='ByTime';
				$viewByValue=$this->params['named']['ByTime'];
				$browseParams[$viewBy]=$viewByValue;
			}
			if(isset($this->params['named']['SortBy'])) 
			{
				$viewBy='SortBy';
				$viewByValue=$this->params['named']['SortBy'];
				$browseParams[$viewBy]=$viewByValue;
			}
			if(isset($this->params['named']['ByCategory'])) 
			{
				$viewBy='ByCategory';
				$viewByValue=$this->params['named']['ByCategory'];
			}
			if(isset($this->params['named']['ischecked'])) 
			{
				$isChecked=$this->params['named']['ischecked'];
			}
			if ($viewBy=='ByCategory')
			{
				if ($viewByValue==$defaultOptions[$viewBy])
				{//case : Previous value = ignore : New value = add 'All categories' option without array
					$browseParams[$viewBy]=$defaultOptions[$viewBy];
				} else {
					$tmpCatList = $browseParams[$viewBy];
					if (!is_array($tmpCatList))
					{//case : Previous value = All Categories : New value = add first categoryId to array
						$browseParams[$viewBy]=array($viewByValue=>$viewByValue); 
					} else {
						if ($isChecked == 0)
						{//unchecked a selected category
							if (count($browseParams[$viewBy])==1) 
							{//case : Previous value = single category in array : New value = add 'All categories' option without array
								$browseParams[$viewBy]=$defaultOptions[$viewBy];
							} else {
								$tmpCatList = array_flip($tmpCatList);
								unset($tmpCatList[$viewByValue]);
								$tmpCatList = array_flip($tmpCatList);
								$browseParams[$viewBy] = $tmpCatList;
							}
						} else {//selected a new category
							$tmpCatList = am($tmpCatList,array($viewByValue=>$viewByValue));
							$browseParams[$viewBy] = $tmpCatList;
						}
					}
				}
			}
			//lines below added if from index page some one click on time options not on browse all events link
			if (!isset($browseParams['ByTime']))
			{
				$browseParams['ByTime']=$defaultOptions['ByTime'];
			}
			if (!isset($browseParams['SortBy']))
			{
				$browseParams['SortBy']=$defaultOptions['SortBy'];
			}
			if (!isset($browseParams['ByCategory']))
			{
				$browseParams['ByCategory']=$defaultOptions['ByCategory'];
			}
		} else {
			$browseParams=$defaultOptions;
		}
		$this->Session->write('eventBrowseParams',$browseParams);
		
		$order = null;
		if ($browseParams['SortBy'] == "Date")
		{
			$order = array("Event.event_from" => "ASC","Event.event_to" => "ASC");
		} else if ($browseParams['SortBy'] == "Most_Popular") {
			$order = array("Event.interested_count" => "DESC");
		} else if ($browseParams['SortBy'] == "Recently_Added") {
			$order = array("Event.created" => "DESC");
		} else if ($browseParams['SortBy'] == "Free") {
			$order = array("Event.event_cost" => "ASC");
		}
		
		$viewBy = $browseParams['ByTime'];
		$condByTime = $this->Event->getSeeByDateCondition($viewBy);	
		
		$viewBy = $browseParams['ByCategory'];
		$condByCat = null;
		if (is_array($viewBy)) {
			$condByCat = array('Event.event_category_id'=>$viewBy);
		} else {
			$condByCat = "1 = 1";
		}
		
		$conditions = array(
			"AND"=>array(
				$condByTime,
				$condByCat
			)
		);
		
		$view_type = 'blog_view';
		$this->set('view_type', $view_type);
		$this->set('loggedInUserId',$this->Session->read('Auth.User.id'));
		$this->set('myTitle',__('Browse Events'));
		
		$this->actionId = 'browseEvents';
		$this->Event->setScope('published');
		
		$eventData = $this->Event->find("all", array('conditions'=>$conditions, 'recursive'=>0,'order'=>$order));
		$this->set('eventData', $eventData);
		
		$this->set('eventCallerName','browseevents');

		/*
		$eventData = $this->Event->find("all", array('conditions'=>$cond));
		if(isset($this->params['requested'])) {
			 return array($eventData,$view_type);
		} 
		$this->set('view_type', $view_type);
		$this->set('eventData', $eventData);
		
		$loggedInUserId = $this->Session->read('Auth.User.id');
		$this->set('loggedInUserId',$loggedInUserId);
		*/
	}

	function otherpopular() 
	{
		$this->Event->setScope('published');
		//$this->pageTitle = __('Other Popular Events');
		//$order = array("(Event.soundscool_count + Event.whosin_count)" => "DESC");
		$order = array("Event.interested_count" => "DESC");
		$view_type = 'table_view';

		$conditions = $this->Event->getOtherPopularEventsCondition();
		
		$otherpopularevents = $this->Event->find("all", array('conditions'=>$conditions,"order"=>$order,"recursive"=>0));
		if(isset($this->params['requested']))
		{
             return array($otherpopularevents,$view_type);
		}
		$this->set('view_type', $view_type);
		$this->set('eventData', $otherpopularevents);
		$this->set('loggedInUserId',$this->Session->read('Auth.User.id'));
		$this->set('eventCallerName','otherpopular');
		$this->render('browse');
	}

	function recentevents() 
	{
		$this->Event->setScope('published');
		//$this->pageTitle = __('Recently Added Events');
		$order = array("Event.created" => "DESC");
		$view_type = 'blog_view';
		$limit = 10;
		$recentevents = $this->Event->find("all",array('order' => $order, 'limit'=>$limit, 'recursive' => 0));
		if(isset($this->params['requested'])) 
		{
            return array($recentevents,$view_type);
        } 
		$this->set('view_type', $view_type);
		$this->set('eventData', $recentevents);
		$this->set('loggedInUserId',$this->Session->read('Auth.User.id'));
		$this->set('eventCallerName','recentevents');
		$this->render('browse');
	}
	
	function generate_cal_file($id = null) 
	{
		$event = $this->Event->find('first', array('conditions' => array('Event.id' => $id),'recursive'=>-1));
		if (!$id || empty($event))
		{
			$this->errorMsg(__('Invalid Request', true));
			$this->redirect($this->referer());
			return;
		}
		else
		{
			$eventStartDate = date("Ymd\THis\Z",strtotime($event['Event']['event_from']));
			$eventEndDate = date("Ymd\THis\Z",strtotime($event['Event']['event_to']));
			$eventUrl = Router::url($event['Event']['viewUrl'], true);
			
			$description = $event["Event"]["description"];
			$flayTextLimit = cr("EventConfig.flay_text");
			if($flayTextLimit && strlen($description) > $flayTextLimit)
			{
				uses("flay");
				$description = Flay::fragment($description, $flayTextLimit);
			}
			
			Configure::write("debug",0);
			$fileName = "calendar.ics";
			$fileBasePath = WWW_ROOT.DS.'uploads'.DS;
			
			$fp = fopen($fileBasePath.$fileName,"w");
			fputs($fp,"BEGIN:VCALENDAR\n");
			fputs($fp,"VERSION:2.0\n");
			fputs($fp,"PRODID:".$eventUrl."\n");
			fputs($fp,"METHOD:REQUEST\n");
			fputs($fp,"BEGIN:VEVENT\n");
			fputs($fp,"DTSTART:".$eventStartDate."\n");
			fputs($fp,"DTEND:".$eventEndDate."\n");
			fputs($fp,"SUMMARY:".$event['Event']['title']."\n");
			fputs($fp,"LOCATION:".$event['Event']['venue']."\n");
			fputs($fp,"DESCRIPTION:".$description."\n");
			fputs($fp,"UID:ABCD1234\n");
			fputs($fp,"SEQUENCE:0\n");
			fputs($fp,"DTSTAMP:".date("Ymd\THis\Z",strtotime(time()))."\n");
			fputs($fp,"END:VEVENT\n");
			fputs($fp,"END:VCALENDAR\n");
			fclose($fp);
			
			$filePath = $fileBasePath.$fileName;
			// Check against path injection
			if (preg_match('/^[A-Za-z0-9_\-\.]*$/', $file) && is_readable($filePath))
			{
				$size = @filesize($filePath);
				if (!headers_sent())
				{
					if ($size > 0)
					{
						header('Content-length: ' . $size);
					}
					header('Content-Type: text/Calendar');
					header('Content-Disposition: inline; filename="'.$fileName.'"');
				}
				readfile($filePath);
				exit;
			}
			return $this->redirect($this->referer()); 
		}
	}
	
	function upcomingevents() 
	{
		$this->Event->setScope('published');
		//$this->pageTitle = __('Upcoming events this week');
		$order = array("Event.event_from" => "ASC");
		$view_type = 'table_view';
		$conditions = $this->Event->getUpcomingEventsCondition();
		
		$upcomingevents = $this->Event->find("all", array('conditions'=>$conditions, "order"=>$order, "recursive"=>0));
		if(isset($this->params['requested'])) 
		{
             return array($upcomingevents,$view_type);
        } 
		$this->set('view_type', $view_type);
		$this->set('eventData', $upcomingevents);
		$this->set('loggedInUserId',$this->Session->read('Auth.User.id'));
		$this->set('eventCallerName','upcomingevents');
		$this->render('browse');
	}

	/*
	function add_subscriber($eventId = null)
	{
		$loggedInUser = $this->Session->read('Auth.User');
		$event = $this->Event->find("first",array("conditions"=>array("Event.id"=>$eventId),"recursive"=>-1));
		if(!$eventId || empty($event) || !$loggedInUser)
		{
			$this->errorMsg(__('Invalid URL', true));
			$this->redirect($this->referer());
		}
		if ($this->Event->EventSubscriber->addSubscriber($eventId, $loggedInUser['id'],$loggedInUser['email'],@$loggedInUser['display_name'])) 
		{
			$this->successMsg(__('Thank you for subscribing to our newsletter.', true));
		} else {
			$this->errorMsg(__('Unable to subscribe! Please try again.', true));
		}
		$this->redirect($this->referer());
	}
	
	function remove_subscriber($eventId = null)
	{
		$loggedInUser = $this->Session->read('Auth.User');
		$event = $this->Event->find("first",array("conditions"=>array("Event.id"=>$eventId),"recursive"=>-1));
		if(!$eventId || empty($event) || !$loggedInUser)
		{
			$this->errorMsg(__('Invalid URL', true));
			$this->redirect($this->referer());
		}
		if($this->Event->EventSubscriber->removeSubscriber($eventId,$loggedInUser))
		{
			$this->successMsg(__('Your name has been removed from our list', true));
		}
		else
		{
			$this->errorMsg(__('There was some problem please try again', true));
		}
		$this->redirect($this->referer());
	}
	*/
	
	function index() 
	{
		if(!isset($this->params['requested']) || $this->params['requested'] != true)
		{
			$this->actionId = 'eventIndex';
		}
		$categoryId=null;
		$eventDate=null;
		$showAddButton = false;
		if($this->Session->read('Auth.User.id'))
		{
			$showAddButton = true;
		}
		$this->set('showAddButton',$showAddButton);
		if(count($this->params['named'])>0)
		{
			if(isset($this->params['named']['categoryId']))
			{
				$categoryId=$this->params['named']['categoryId'];
			}
			if(isset($this->params['named']['eventDate']))
			{
				$eventDate=$this->params['named']['eventDate'];
			}
		}
		$this->Event->setScope('published');
		$this->paginate['recursive'] = 0;
		//$this->Event->recursive = 0;
		$view_type = 'blog_view';
		$this->set('view_type', $view_type);
		$this->set('categories',$this->Event->EventCategory->find('list'));
		//if(($categoryId==null || $categoryId=='0') || ($eventDate==null || $eventDate=='')){
		if(count($this->params['named'])==0){
			$this->set('events', array());
			$this->set('categoryId',null);
		}
		else
		{
			//$order = array("(Event.soundscool_count + Event.whosin_count)" => "DESC");
			$order = array("Event.interested_count" => "DESC");
			$this->Event->order = $order;
			if($categoryId==null || $categoryId=='0')
			{
				$events = $this->paginate();
				$this->set('events', $events);
			}
			else if ($categoryId!=null)
			{
				$cond = array('Event.event_category_id'=>$categoryId);
				$events = $this->paginate("Event", $cond);
				$this->set('events', $events);
			}
			
			/*
			if(($categoryId==null || $categoryId=='0') && $eventDate==null){
				$this->set('events', $this->paginate());
			}
			if($categoryId!=null && $eventDate!=null){
				$cond = array(
						'Event.event_category_id'=>$categoryId,
						'Date(Event.event_from) <='=>date('Ymd',strtotime($eventDate)),
						'Date(Event.event_to) >='=>date('Ymd',strtotime($eventDate))
				);
				$this->set('events', $this->paginate("Event", $cond));
			}
			if($categoryId!=null && $eventDate==null)
			{
				$cond = array('Event.event_category_id'=>$categoryId);
				$this->set('events', $this->paginate("Event", $cond));
			}
			if(($categoryId==null || $categoryId=='0') && $eventDate!=null)
			{
				$cond = array(
						'Date(Event.event_from) <='=>date('Ymd',strtotime($eventDate)),
						'Date(Event.event_to) >='=>date('Ymd',strtotime($eventDate))
				);
				$this->set('events', $this->paginate("Event", $cond));
			}
			$this->set('categoryId',$categoryId);
			*/
		}
		if(count($this->params['named'])==0)
		{
			$this->set('beingReloaded',0);
			//$this->theme = 'electronics';
		}
		else
		{
			$this->set('beingReloaded',1);
			//$this->theme = 'default';
		}
		$this->set('isPosterEditAllowed',cr("EventConfig.allowPosterEdit"));
		$this->set('isPosterDeleteAllowed',cr("EventConfig.allowPosterDelete"));
		$this->set('loggedInUserId',$this->Session->read('Auth.User.id'));
	}
	
	function view($event_slug = null)
	{
		$loggedInUser = $this->Session->read('Auth.User.id');
		$eventData = $this->Event->find('first',array('conditions'=>array('Event.slug'=>$event_slug,'Event.status'=> Event::PUBLISH),'recursive'=>0));
		if (!$event_slug || empty($eventData)) 
		{
			$this->errorMsg(__('Invalid Event', true));
			$this->redirect(array('action' => 'index'));
			return;
		}
		if(!isset($this->params['requested']) || $this->params['requested'] != true)
		{
			$this->actionId = 'eventView';
		}
		
		$this->Event->id = $eventData['Event']['id'];
		$this->Event->saveField('views_count',++$eventData['Event']['views_count'], false, false);
		$eventData = $this->Event->appendLocationInformation($eventData);
		
		$showEditLink = false;
		if(cr("EventConfig.allowPosterEdit") && !is_null($loggedInUser) && $eventData['Event']['user_id']==$loggedInUser){
			$showEditLink=true;
		}
		$showDeleteLink = false;
		if(cr("EventConfig.allowPosterDelete") && !is_null($loggedInUser) && $eventData['Event']['user_id']==$loggedInUser){
			$showDeleteLink=true;
		}
		$isSubscriber = false;
		if($loggedInUser) {
			$isSubscriber = $this->Event->EventSubscriber->isSubscriber($eventData['Event']['id'],$loggedInUser);
		}
		
		$interestedUsers = $this->Event->EventInterest->getInterestedUsers($eventData['Event']['id']);
		$isLoggedInUserInterested = $this->Event->EventInterest->isInterested($eventData['Event']['id'], $loggedInUser);
		$attendingUsers = $this->Event->EventAttendee->getAttendees($eventData['Event']['id']);
		$isLoggedInUserAttending = $this->Event->EventAttendee->isAttendee($eventData['Event']['id'], $loggedInUser);
		$eventAssets = $this->Event->EventAsset->find('all',array('conditions'=>array('status'=>EventAsset::PUBLISHED,'EventAsset.is_default'=>0,'EventAsset.event_id'=>$eventData['Event']['id']),'order'=>array('EventAsset.created DESC'),'recursive'=>-1));
		$listing = cri("Listing")->find("first",array("conditions"=>array("Listing.id"=>$eventData['Event']['listing_id']),"recursive"=>0));
		$this->Event->EventComment->unbindModel(array('belongsTo'=>array('Listing')));
		$comments = $this->Event->EventComment->find('all',array('conditions'=>array('EventComment.event_id'=>$eventData['Event']['id']),'recursive'=>0));
		
		$this->set(compact('eventAssets','comments','interestedUsers','attendingUsers','listing','loggedInUser','isLoggedInUserInterested','isLoggedInUserAttending'));
		$this->set('eventIdForWhosIn',$eventData['Event']['id']);
		$this->set('event', $eventData);
		$this->set('showEditLink',$showEditLink);
		$this->set('showDeleteLink',$showDeleteLink);
		$this->set("isSubscriber",$isSubscriber);
		
		$this->pageTitle = $eventData['Event']['title'];
		$this->helpers[] = "GeoMap";
	}

	function add($listingId = null)
	{
		$authedUserId = $this->Session->read('Auth.User.id');
		$ListingModel = cri("Listing");
		$ListingModel->setScope('published');
		$listing = $ListingModel->find("first",array("conditions"=>array("Listing.id"=>$listingId),"recursive"=>-1));
		if($listingId && !empty($listing))
		{
			if(cr("EventConfig.onlyOwnerCanAddEvent") && !$ListingModel->isOwner($listingId, $authedUserId))
			{
				$this->errorMsg(__("Only the owner of the listing can add events", true));
				$this->redirect("/");
				return;
			}
		}
		$this->actionId = 'eventAdd';
		
		$this->Event->setListingFieldProperties($listingId);
		
		if (!empty($this->data)) 
		{
			if($listingId && !empty($listing) && (!isset($this->data['Event']['listing_id']) || !$this->data['Event']['listing_id']))
			{
				$this->data['Event']['listing_id']=$listingId;
			}
			$this->data['Event']['user_id'] = $authedUserId;
			if(isset($this->data['Event']['listing_id']) && $this->data['Event']['listing_id'])
			{
				if($this->Event->hasActiveEventsLimitCrossed($this->data['Event']['listing_id']))
				{
					$this->errorMsg(__("Event limit exhausted", true));
					$this->redirect(array('action' => 'index'));
					return;
				}
			}
			$moderationRequired = cr("EventConfig.enable_moderation");
			if($moderationRequired)
			{
				$this->data['Event']['status'] = Event::UNPUBLISH;
			}
			else
			{
				$this->data['Event']['status'] = Event::PUBLISH;
			}
			if ($this->save($this->data,false)) 
			{
				if ($moderationRequired) 
				{
					$this->successMsg(__('The Event has been saved and will be published after moderation.'));
				} else {
					$this->successMsg(__('The Event has been saved', true));
				}
				$this->redirect(array('action' => 'index'));
			} else {
				$this->errorMsg(__('The Event could not be saved. Please, try again.', true));
			}
			$this->set('isFreeDefaultValue', false);
		} else {
			/*
			if($listingId && !empty($listing))
			{
				$this->data['Event']['listing_id'] = $listingId;
				$this->data['Event']['listing_text'] = $listing["Listing"]["title"];
			}
			*/
			$this->set('isFreeDefaultValue', true);
		}
		if(!empty($listing))
		{
			$this->pageTitle = sprintf(__("Add event for listing: %s",true),$listing['Listing']['title']);
		} else {
			$this->pageTitle = __("Add event",true);
		}
		/*
		$eventDefaultFieldProperties = array();
		$eventDefaultFields = $this->Event->getDefaultFields();
		foreach($eventDefaultFields as $fieldName)
		{
			$eventDefaultFieldProperties[$fieldName] = $this->Event->getFieldProperties($fieldName);
		}
		$this->set("eventDefaultFields",$eventDefaultFieldProperties);
		*/
		$eventCategories = $this->Event->EventCategory->find('list');
		$this->set(compact('eventCategories','listing','listingId'));
	}

	function edit($event_slug = null) 
	{
		$authedUserId = $this->Session->read('Auth.User.id');
		$this->Event->setScope('published');
		$this->actionId = 'eventEdit';
		$eventData  = $this->Event->find("first",array("conditions"=>array("Event.slug"=>$event_slug,"Event.user_id"=>$authedUserId),'recursive'=>-1));
		if (!$event_slug || !$eventData || empty($eventData)) 
		{
			$this->errorMsg(__('Invalid URL', true));
			$this->redirect(array('action' => 'index'));
			return;
		}
		if(!cr("EventConfig.allowPosterEdit"))
		{
			$this->errorMsg(__('Editing not allowed', true));
			$this->redirect(array('action' => 'index'));
			return;
		}
		
		$listing = cri("Listing")->find("first",array("conditions"=>array("Listing.id"=>$eventData['Event']['listing_id']),"recursive"=>-1));

		if ($this->data) 
		{
			$this->data['Event']['status'] = $eventData['Event']['status'];
			$this->data['Event']['id'] = $eventData['Event']['id'];
			$this->data['Event']['user_id']=$authedUserId;
			$moderationRequired = cr("EventConfig.enable_moderation");
			if($moderationRequired)
			{
				$this->data['Event']['status'] = Event::UNPUBLISH;
			}
			if($this->save($this->data,true))
			{
				$msg = __('Event has been updated.', true);
				
				$this->Event->clearScope('published');
				$eventData  = $this->Event->find("first",array("conditions"=>array("Event.id"=>$eventData["Event"]['id']),'recursive'=>-1));
				$this->Event->setScope('published');
				
				$url = $eventData['Event']['viewUrl'];
				if($eventData['Event']['status'] == Event::UNPUBLISH)
				{
					$msg = __("Event has been updated and will be published after moderation.", true);
					$url = array('action'=>"index");
				}
				$this->successMsg($msg);
				$this->redirect($url);
			} else {
				$this->errorMsg(__('Event could not be updated! Please try again', true));
			}
		}
		else
		{
			$this->data = $eventData;
			$this->data['Event']['listing_text'] = $listing['Listing']['title'];
			$this->data['Event']['listing_id'] = $listing['Listing']['id'];
		}
		//$this->pageTitle = $eventData['Event']['title'];
		
		$eventAssets = $this->Event->EventAsset->find('all',array("conditions"=>array("EventAsset.status"=>EventAsset::PUBLISHED,'EventAsset.event_id'=>$eventData['Event']['id']),'recursive'=>-1));
		
		$eventCategories = $this->Event->EventCategory->find('list');
		$eventDefaultFieldProperties = array();
		$eventDefaultFields = $this->Event->getDefaultFields();
		foreach($eventDefaultFields as $fieldName)
		{
			/*
			if($fieldName == 'event_category_id')
			{//to avoid editing of category by a non-admin user
				continue;
			}
			*/
			$eventDefaultFieldProperties[$fieldName] = $this->Event->getFieldProperties($fieldName);
		}
		$this->pageTitle = sprintf(__("Edit %s", true), $eventData["Event"]["title"]);
		// //$this->set("eventData",$eventData);
		$this->set("eventDefaultFields",$eventDefaultFieldProperties);
		$this->set("showImageTab",true);
		$this->set("event",$eventData);
		$this->set("eventAssets",$eventAssets);
		$this->set(compact('eventCategories','listing'));
		$this->helpers[] = "Tabs";
		$this->helpers[] = "Assets.Asset";
	}

	function delete($id = null) 
	{
		$authedUserId = $this->Session->read('Auth.User.id');
		$event = $this->Event->find("first",array("conditions"=>array("Event.id"=>$id, "Event.user_id"=>$authedUserId),"recursive"=>-1));
		if (!$id || !$event || !$authedUserId) 
		{
			$this->errorMsg(__('Invalid URL', true));
			$this->redirect(array('action' => 'index'));
			return;
		}
		if(!cr("EventConfig.allowPosterDelete"))
		{
			$this->errorMsg(__('You do not have permission to delete this record', true));
			$this->redirect(array('action' => 'index'));
			return;
		}
		if ($this->Event->del($id))
		{
			$this->successMsg(__('Event deleted successfully', true));
		} else {
			$this->errorMsg(__('The Event could not be deleted. Please, try again.', true));
		}
		$this->redirect(array('action' => 'index'));
	}


	function admin_index() 
	{
		if(isset($this->params['named']['search']))
		{
			$this->admin_search();
		}
		else
		{
			if(isset($this->params['named']['category']))
			{
				$eventCategoryId = $this->params['named']['category'];
				$this->Event->event_category_id = $eventCategoryId;
				$this->paginate['conditions'] = array('Event.event_category_id'=>$eventCategoryId);
			}

			$this->paginate['limit'] = 10;
			$this->paginate['recursive'] = 0;
			$this->paginate['order'] = array("Event.created" => "DESC");
			$events = $this->paginate();
			$this->set('events', $events);
			
			$categories = $this->Event->EventCategory->find('list', array('fields'=>array('EventCategory.id','EventCategory.name'),'order'=>array('name')));
			$this->set('categories', $categories);
			$listingIds = Set::extract("{n}.Event.listing_id",$events);
			$listings = cri("Listing")->find("all",array("conditions"=>array("Listing.id" => $listingIds),"recursive"=>-1));
			$listings = Set::combine($listings,"{n}.Listing.id","{n}");
			$this->set("listings",$listings);
		}
	}

	function admin_changeStatus($id = null)
	{
		$eventData = $this->Event->find('first',array('conditions'=>array('Event.id'=>$id),'recursive'=>-1));
		if(empty($eventData))
		{
			$this->errorMsg(__('Invalid URL'));
			$this->redirect($this->referer());
		}
		$eventStatus = $eventData['Event']['status'];
		if($eventStatus == Event::PUBLISH)
		{
			$statusToSave = Event::UNPUBLISH;
			$successMessage =  __('Event has been unpublished.');
			$errorMessage =  __('Event could not be unpublished.');
		} else {
			if(isset($eventData['Event']['listing_id']) && $eventData['Event']['listing_id'])
			{
				if($this->Event->hasActiveEventsLimitCrossed($eventData['Event']['listing_id']))
				{
					$this->errorMsg(__("Event limit exhausted", true));
					$this->redirect($this->referer());
					return;
				}
			}
			$statusToSave = Event::PUBLISH;
			$successMessage =  __('Event has been published.');
			$errorMessage = __('Event could not be published.');
		}
		$this->Event->id = $id;
		if($this->Event->saveField('status',$statusToSave))
		{
			$this->successMsg($successMessage);
		} else {
			$this->errorMsg($errorMessage);
		}
		$this->redirect($this->referer());
	}

	function admin_search()
	{
		//$this->pageTitle = __('Search');
		$default = array(
				'title'=>'',
				'submitter_name'=>'',
				'event_category_id'=>'',
				'status'=>'',
		);
		if($this->data)
		{
			$queryString = '';
			foreach($this->data['Event'] as $field=>$value)
			{
				$queryString .= $field.':'.$value.'/';
			}
			//$url = am(array('action'=>'search','prefix'=>'admin'),$this->data['Event']);
			$this->redirect('/admin/events/events/search/'.$queryString);
		}
		$this->paginate['limit'] = 10;
		$params = am($default,$this->params['named']);

		if(!empty($params['title']))
		{
			$this->paginate['conditions']['AND'][] = array('Event.title LIKE'=>'%'.$params['title'].'%');
		}
			
		if(!empty($params['submitter_name']))
		{
			$user_ids = $this->Event->User->find('list',array('fields'=>'User.id','conditions'=>array('User.username LIKE'=>'%'.$params['submitter_name'].'%')));
			$this->paginate['conditions']['AND'][] = array('Event.user_id'=>$user_ids);
		}
			
		if(!empty($params['event_category_id']))
		{
			$categoryIds = $params['event_category_id'];
			$this->Event->event_category_id = $categoryIds;
			$this->paginate['conditions']['AND'][] = array('Event.event_category_id'=>$categoryIds);
		}
			
		if($params['status'] !=='')
		{
			if($params['status'] == 'featured')
			{
				$this->paginate['conditions']['AND'][] = array('Event.is_featured'=>1);
			}else{
				$this->paginate['conditions']['AND'][] = array('Event.status'=>$params['status']);
			}
		}
		$this->paginate['contain'] = array('EventCategory');
		$this->paginate['order'] = array('Event.created DESC');
		$this->paginate['limit'] = 10;
		//$this->paginate['recursive'] = -1;
		if(isset($this->params['named']['page']) || isset($this->params['named']['limit']))
		{
			$this->paginate['conditions'] = $this->Session->read('conditions');
		}elseif(isset($this->paginate['conditions']))
		{
			$this->Session->write('searchParams',$params);
			$this->Session->write('conditions',$this->paginate['conditions']);
		}
		$events = $this->paginate();
		$this->set('events',$events);

		$categories = $this->Event->EventCategory->find('list', array('fields'=>array('EventCategory.id','EventCategory.name'),'order'=>array('EventCategory.name')));
		$this->set('categories', $categories);

		$listingIds = Set::extract("{n}.Event.listing_id",$events);
		$listings = cri("Listing")->find("all",array("conditions"=>array("Listing.id" => $listingIds),"recursive"=>-1));
		$listings = Set::combine($listings,"{n}.Listing.id","{n}");
		$this->set("listings",$listings);
		
		$this->render('admin_index');
	}


	function admin_view($id = null) 
	{
		if (!$id) {
			$this->errorMsg(__('Invalid Event', true));
			$this->redirect(array('action' => 'index'));
		}
		$eventData = $this->Event->find('first',array('conditions'=>array('Event.id'=>$id),'recursive'=>0));
		if (!$eventData) {
			$this->errorMsg(__('Invalid Event', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->Event->id = $id;
		$this->Event->saveField('views_count',++$eventData['Event']['views_count'], false, false);
		$eventData = $this->Event->appendLocationInformation($eventData);

		$eventAssets = $this->Event->EventAsset->find('all',array('conditions'=>array('EventAsset.status'=>EventAsset::PUBLISHED,'EventAsset.is_default'=>0,'EventAsset.event_id'=>$id),'order'=>array('EventAsset.created DESC'),'recursive'=>-1));
		$attendees = $this->Event->EventAttendee->getAttendees($id);
		$interested = $this->Event->EventInterest->getInterestedUsers($id);
		
		$comments = $this->Event->EventComment->find('all',array('conditions'=>array('EventComment.event_id'=>$id),'recursive'=>-1));
		$listing = cri("Listing")->find('first',array('recursive'=>0,'conditions'=>array('Listing.id'=>$eventData['Event']['listing_id'])));
		
		$this->pageTitle = $eventData["Event"]["title"];
		
		$this->set(compact('eventAssets'));
		$this->set("showAttending",0);
		$this->set("showSoundsCool",0);
		$this->set('interested',$interested);
		$this->set('attendees',$attendees);
		$this->set('loggedInUser',null);
		$this->set('comments', $comments);
		$this->set('event', $eventData);
		$this->set('listing',$listing);
		$this->helpers[] = "GeoMap";
	}

	function admin_add($listingId = null) 
	{
		$ListingModel = cri("Listing");
		$listing = $ListingModel->find("first",array("conditions"=>array("Listing.id"=>$listingId),"recursive"=>-1));
		
		$this->Event->setListingFieldProperties($listingId);
		
		if(!empty($this->data))
		{
			//prd($this->data);exit;
			if($listingId && !empty($listing) && (!isset($this->data['Event']['listing_id']) || !$this->data['Event']['listing_id']))
			{
				$this->data['Event']['listing_id']=$listingId;
			}
			$this->data['Event']['user_id']=null;
			$this->data['Event']['status']=Event::PUBLISH;
			
			if(isset($this->data['Event']['listing_id']) && $this->data['Event']['listing_id'])
			{
				if($this->Event->hasActiveEventsLimitCrossed($this->data['Event']['listing_id']))
				{
					$this->errorMsg(__("Event limit exhausted", true));
					$this->redirect(array('action' => 'index'));
					return;
				}
			}
			if ($this->save($this->data)) 
			{
				$this->successMsg(__('The Event has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->errorMsg(__('The Event could not be saved. Please, try again.', true));
			}
			$this->set('isFreeDefaultValue', false);
		} else {
			/*
			if($listingId && !empty($listing))
			{
				$this->data['Event']['listing_id'] = $listingId;
				$this->data['Event']['listing_text'] = $listing["Listing"]["title"];
			}
			*/
			$this->set('isFreeDefaultValue', true);
		}
		if(!empty($listing))
		{
			$this->pageTitle = sprintf(__("Add event for listing: %s",true),$listing['Listing']['title']);
		} else {
			$this->pageTitle = __("Add event",true);
		}
		/*
		$eventDefaultFieldProperties = array();
		$eventDefaultFields = $this->Event->getDefaultFields();
		foreach($eventDefaultFields as $fieldName)
		{
			$eventDefaultFieldProperties[$fieldName] = $this->Event->getFieldProperties($fieldName);
		}
		$this->set("eventDefaultFields",$eventDefaultFieldProperties);
		*/
		$eventCategories = $this->Event->EventCategory->find('list');
		$this->set(compact('eventCategories','listing','listingId'));
		$this->render("add");
	}


	function admin_edit($id = null) 
	{
		//$this->Event->setScope('published');
		$eventData = $this->Event->find("first",array("conditions"=>array("Event.id"=>$id),'recursive'=>-1));
		if (!$id || !$eventData || empty($eventData)) 
		{
			$this->errorMsg(__('Invalid Event', true));
			$this->redirect(array('action' => 'index'));
		}
		$listing = cri("Listing")->find("first",array("conditions"=>array("Listing.id"=>$eventData['Event']['listing_id']),"recursive"=>-1));
		if ($this->data) 
		{
			$this->data['Event']['status'] = $eventData['Event']['status'];
			$this->data['Event']['id'] = $eventData['Event']['id'];
			$this->data['Event']['user_id'] = $eventData['Event']['user_id'];
			
			if($this->save($this->data,true))
			{
				$msg = __('Event has been updated.');
				$url = array('action'=>'view',$id);
				if($eventData['Event']['status'] == Event::UNPUBLISH)
				{
					$msg = __("Event has been updated and will be published after moderation.", true);
					$url = array('action'=>"index");
				}
				$this->successMsg($msg);
				$this->redirect($url);
			} else {
				$this->errorMsg(__('Event could not be updated! Please try again', true));
			}
		}
		else
		{
			$this->data = $eventData;
			$this->data['Event']['listing_text'] = $listing['Listing']['title'];
			$this->data['Event']['listing_id'] = $listing['Listing']['id'];
		}

		$eventAssets = $this->Event->EventAsset->find('all',array("conditions"=>array("EventAsset.status"=>EventAsset::PUBLISHED,'EventAsset.event_id'=>$eventData['Event']['id']),'recursive'=>-1));
		$eventCategories = $this->Event->EventCategory->find('list');
		
		$eventDefaultFieldProperties = array();
		$eventDefaultFields = $this->Event->getDefaultFields();
		foreach($eventDefaultFields as $fieldName)
		{
			$eventDefaultFieldProperties[$fieldName] = $this->Event->getFieldProperties($fieldName);
		}
		$this->set("eventDefaultFields",$eventDefaultFieldProperties);
		$this->pageTitle = sprintf(__("Edit %s", true), $eventData["Event"]["title"]);
		$this->set(compact('eventCategories','listing'));
		$this->set("showImageTab",true);
		$this->set("event",$eventData);
		$this->set("eventAssets",$eventAssets);
		
		$this->helpers[] = "Tabs";
		$this->helpers[] = "Assets.Asset";
		$this->render("edit");
	}

	function admin_delete($id = null) 
	{
		if (!$id) 
		{
			$this->errorMsg(__('Invalid URL', true));
			$this->redirect($this->referer());
		}
		if ($this->Event->del($id)) 
		{
			$this->successMsg(__('Event deleted successfully', true));
		} else {
			$this->errorMsg(__('The Event could not be deleted. Please, try again.', true));
		}
		$this->redirect($this->referer());
	}

	function _valDates() 
	{
		$ff = $this->data['Event']['event_from'];
		$ff = $ff['year'].'-'.$ff['month'].'-'.$ff['day'].' '.$ff['hour'].':'.$ff['min'].':00';
		$tt = $this->data['Event']['event_to'];
		$tt = $tt['year'].'-'.$tt['month'].'-'.$tt['day'].' '.$tt['hour'].':'.$tt['min'].':00';

		$newEventFrom = strtotime($ff);
		$newEventTo = strtotime($tt);
		$oldEventFrom=strtotime($this->data['Event']['old_event_from']);
		$oldEventTo=strtotime($this->data['Event']['old_event_to']);
		$currentTime = time();
		if($newEventFrom != $oldEventFrom)
		{
			if($oldEventFrom < $currentTime){
				$msgDate = 'There is no point in changing <b>Event From</b> since it has already passed';
				return false;
			}
		}

		if($newEventTo != $oldEventTo)
		{
			if($oldEventTo < $currentTime){
				$msgDate = 'There is no point in changing <b>Event To</b> since it has already passed';
				return false;
			}
		}
		return true;
	}

	
	function add_attendee($eventId = null)
	{
		$loggedInUser = $this->Session->read('Auth.User.id');
		$event = $this->Event->find("first",array("conditions"=>array("Event.id"=>$eventId),"recursive"=>-1));
		if(!$eventId || empty($event) || !$loggedInUser)
		{
			$this->errorMsg(__('Invalid URL', true));
			$this->redirect($this->referer());
		}
		if($this->Event->EventAttendee->addAttendee($eventId,$loggedInUser))
		{
			$this->Event->id = $eventId;
			$this->Event->saveField('interested_count',($event['Event']['soundscool_count']+$event['Event']['whosin_count']+1));
			$this->successMsg(__('Your choice has been saved', true));
		}
		else
		{
			$this->errorMsg(__('Your choice could not be saved', true));
		}
		$this->redirect($this->referer());
	}
	
	function revoke_attendee($eventId = null)
	{
		$loggedInUser = $this->Session->read('Auth.User.id');
		$event = $this->Event->find("first",array("conditions"=>array("Event.id"=>$eventId),"recursive"=>-1));
		if(!$eventId || empty($event) || !$loggedInUser)
		{
			$this->errorMsg(__('Invalid URL', true));
			$this->redirect($this->referer());
		}
		if($this->Event->EventAttendee->revokeAttendee($eventId,$loggedInUser))
		{
			$interestedCount = (($event['Event']['soundscool_count']+$event['Event']['whosin_count'])-1);
			if($interestedCount < 0)
			{
				$interestedCount = 0;
			}
			$this->Event->id = $eventId;
			$this->Event->saveField('interested_count',$interestedCount);
			$this->successMsg(__('Your attendance has been revoked', true));
		}
		else
		{
			$this->errorMsg(__('Your attendance could not be revoked', true));
		}
		$this->redirect($this->referer());
	}

	function add_soundscool($eventId = null)
	{
		$loggedInUser = $this->Session->read('Auth.User.id');
		$event = $this->Event->find("first",array("conditions"=>array("Event.id"=>$eventId),"recursive"=>-1));
		if(!$eventId || empty($event) || !$loggedInUser)
		{
			$this->errorMsg(__('Invalid URL', true));
			$this->redirect($this->referer());
		}
		if($this->Event->EventInterest->AddInterest($eventId,$loggedInUser))
		{
			$this->Event->id = $eventId;
			$this->Event->saveField('interested_count',($event['Event']['soundscool_count']+$event['Event']['whosin_count']+1));
			$this->successMsg(__('Your choice is saved', true));
		}
		else
		{
			$this->errorMsg(__('Your choice could not be saved', true));
		}
		$this->redirect($this->referer());
	}
	
	function revoke_soundscool($eventId = null)
	{
		$loggedInUser = $this->Session->read('Auth.User.id');
		$event = $this->Event->find("first",array("conditions"=>array("Event.id"=>$eventId),"recursive"=>-1));
		if(!$eventId || empty($event) || !$event || !$loggedInUser)
		{
			$this->errorMsg(__('Invalid URL', true));
			$this->redirect($this->referer());
		}
		if($this->Event->EventInterest->revokeInterest($eventId, $loggedInUser))
		{
			$interestedCount = (($event['Event']['soundscool_count']+$event['Event']['whosin_count'])-1);
			if($interestedCount < 0)
			{
				$interestedCount = 0;
			}
			$this->Event->id = $eventId;
			$this->Event->saveField('interested_count',$interestedCount);
			$this->successMsg(__('Your interest has been revoked', true));
		}
		else
		{
			$this->errorMsg(__('Your interest could not be revoked', true));
		}
		$this->redirect($this->referer());
	}
	
	function add_comment() {//eventId is passed
		if(!isset($_POST)){
			$this->errorMsg(__('Invalid Request', true));
			$this->redirect($this->referer());
		}
		if(!(isset($_POST['data']['Event']['comment']) && isset($_POST['data']['Event']['eventId']))){
			$this->errorMsg(__('Invalid Request', true));
			$this->redirect($this->referer());
		}
		$loggedInUser = $this->Session->read('Auth.User.id');
		if(!$loggedInUser || empty($loggedInUser))
		{
			$this->errorMsg(__('Authentication Failure', true));
			$this->redirect($this->referer());
		}
		$eventId = $_POST['data']['Event']['eventId'];
		$comment = $_POST['data']['Event']['comment'];
		$currEvent = $this->Event->findById($eventId);
		$this->Event->EventComment->saveField('event_id',$eventId);
		$this->Event->EventComment->saveField('user_id',$loggedInUser);		
		$this->Event->id = $eventId;
		/* commented as this is now handled by counterCache
		 * if($this->Event->saveField('comment_count',$currEvent['Event']['comment_count']+1, false, false)){
		 */		
		if($this->Event->EventComment->saveField('description',$comment)){
			$this->successMsg(__('Your comment has been saved', true));
			$this->_sendNewCommentEmail($eventId);
		}
		else
		{
			$this->errorMsg(__('Your comment could not be saved', true));
		}

		$this->redirect($this->referer());
	}
	function delete_comment($commentId = null)
	{
		$loggedInUser = $this->Session->read('Auth.User.id');
		
		if(!$commentId)
		{
			$this->errorMsg(__('Invalid Comment', true));
			$this->redirect($this->referer());
		}
		if(!$loggedInUser || empty($loggedInUser))
		{
			$this->errorMsg(__('Authentication Failure', true));
			$this->redirect($this->referer());
		}
		$comment = $this->Event->EventComment->findById($commentId);
		$currEvent = $this->Event->findById($comment['EventComment']['event_id']);
		if($this->Event->EventComment->delete($comment)){
			$this->Event->id=$currEvent['Event']['id'];
			/* commented as this is now handled by counterCache
			 * $this->Event->saveField('comment_count',$currEvent['Event']['comment_count']-1, false, false); 
			 */
			$this->successMsg(__('Your comment has been deleted', true));
		}
		else
		{
			$this->errorMsg(__('Your comment could not be deleted', true));
		}
		$this->redirect($this->referer());

	}

	function admin_delete_comment($commentId = null)
	{
		$comment = $this->Event->EventComment->findById($commentId);
		if(!$commentId || !$comment)
		{
			$this->errorMsg(__('Invalid Comment', true));
			$this->redirect($this->referer());
		}
		$currEvent = $this->Event->findById($comment['EventComment']['event_id']);
		if($this->Event->EventComment->delete($comment)){
			$this->Event->id=$currEvent['Event']['id'];
			/* commented as this is now handled by counterCache
			 * $this->Event->saveField('comment_count',$currEvent['Event']['comment_count']-1, false, false); 
			 */

			$this->successMsg(__('The comment has been deleted', true));
		}
		else
		{
			$this->errorMsg(__('The comment could not be deleted', true));
		}
		$this->redirect($this->referer());
	}

	

	protected function save($data = null,$editing = false)
	{
		/* to handle disabled text boxes*/
		if(!isset($data['Event']['event_cost']))
		{
			$data['Event']['event_cost']=0;			
		}
		if(!isset($data['Event']['event_cost_to']))
		{
			$data['Event']['event_cost_to']=0;
		}
		$data['Event']['title']=ucwords($data['Event']['title']);
		/* to handle disabled text boxes*/
		
		$this->Event->create();
		$defaultEventAssetId = null;
		if($editing && isset($data['EventAsset']['is_default']))
		{
			$defaultEventAssetId = $data['EventAsset']['is_default'];
		}
		unset($data['EventAsset']['is_default']);
		if(empty($data['EventAsset']))
		{
			unset($data['EventAsset']);
		}
		if($this->Event->saveAll($data,array('validate'=>'first')))
		{
			if($defaultEventAssetId)
			{
				$this->Event->EventAsset->makeAsDefault($this->Event->id,$defaultEventAssetId);
			}
			return true;
		} else {
			return false;
		}
	}

	function _sendNewCommentEmail($eventId = null)
	{
		if($eventId)
		{
			$this->Event->id = $eventId;
			$this->Event->recursive=-1;
			//$eventData = $this->Event->findById($eventId);
			$eventData = $this->Event->find('first',array('conditions'=>array('Event.id'=>$eventId),'fields'=>array('Event.title','Event.slug')));
			$this->Event->EventSubscriber->recursive=-1;
			$subscribers = $this->Event->EventSubscriber->find('all',array('conditions'=>array('EventSubscriber.event_id'=>$eventId),'fields'=>array('EventSubscriber.name','EventSubscriber.email')));
			if(!empty($subscribers))
			{
				$this->Email->reset();
				foreach($subscribers as $subscriber)
				{
					$this->Email->to = $subscriber['EventSubscriber']['email'];
					$this->Email->setFrom(cr('cmsConfig.Backend.websiteEmail'),cr('cmsConfig.Backend.siteName'));
					$this->Email->subject = __('Comment added on your subscribed event');
					$this->Email->template = 'event_new_comment';
					$this->Email->sendAs = 'both';
					$this->set('username',$subscriber['EventSubscriber']['name']);
					$this->set('eventTitle',$eventData['Event']['title']);
					$this->set('eventUrl',cr('cmsConfig.Backend.siteUrl').'/events/view/'.$eventData['Event']['slug'].'/#event_comments');
					$this->Email->send();
					$this->Email->reset();
				}
			}
		}
		return true;
	}
	
	
	
	function whosin($eventId=null) {				
		if(!isset($this->params['requested']) || $this->params['requested'] != true)
		{
			$this->actionId = 'eventWhosin';
		}
		if($eventId==null){
			return true;
		}
		$this->Event->EventAttendee->recursive=1;
		$attendees = $this->Event->EventAttendee->findAllByEventId($eventId);
		$this->set('attendees',$attendees);
		$this->Event->EventInterest->recursive=1;
		$interested = $this->Event->EventInterest->findAllByEventId($eventId);
		$this->set('interested',$interested);
		if(isset($this->params['requested'])) {
             return array($attendees,$interested);
        } 
	}
	
	
	function suggestListings()
	{
		$q = null;
		if(isset($_GET['q']))
		{
			$q = $_GET['q'];
		}
		Configure::write("debug",0);
		$q = trim($q);
		$suggestions = array();
		$limit = 15;
		
		App::import('Model','Listing');
		$ListingModel = cri('Listing');
		//prd($ListingModel); 
		$condition = $ListingModel->getTextSearchCondition($q,true);
		$condition['AND']['Listing.status'] = Listing::PUBLISH;
		$suffixMsg = '';
		if(cr("EventConfig.onlyOwnerCanAddEvent") && $this->Session->read('Auth.User.id'))
		{
			$condition[] = array("Listing.owner_id" => $this->Session->read('Auth.User.id'));
			$condition[] = array("NOT" => array("Listing.owner_id"=>NULL));
			$suffixMsg = __("You should be the owner of listing to add an event.");
		}
		$listings = $ListingModel->find('list',array('conditions'=>$condition,'fields'=>array("Listing.id","Listing.title"),'limit'=>$limit,'recursive'=>-1));
		//pr($condition);
		if(count($listings))
		{
			foreach($listings as $listingId=>$listingTitle)
			{
				echo $listingTitle.'|'.$listingId."\n";
			}
		}
		else
		{
			echo __("No result").". ".$suffixMsg;
		}
		exit;
	}
	
	function newsletter($limit = 10)
	{
		Configure::write('debug',0);
		$this->layout = 'ajax';
		$events = $this->Event->getEventsForNewsletter($limit);
		$this->set('events',$events);
	}

	function admin_suggestListings()
	{
		$q = null;
		if(isset($_GET['q']))
		{
			$q = $_GET['q'];
		}
		Configure::write("debug",0);
		$q = trim($q);
		$suggestions = array();
		$limit = 15;
		App::import('Model','Listing');
		//$listing = new Listing();
		$ListingModel = cri("Listing");
		$condition = $ListingModel->getTextSearchCondition($q,true);
		$condition['AND']['Listing.status'] = Listing::PUBLISH;
		//$listing->Behaviors->detach("Eav");
		$ListingModel->setEavStatus(false);
		$listings = $ListingModel->find('list',array('conditions'=>$condition,'fields'=>array("Listing.id","Listing.title"),'limit'=>$limit,'recursive'=>-1));
		
		if(count($listings))
		{
			foreach($listings as $suggest)
			{
				echo $suggest['Listing']['title'].'|'.$suggest['Listing']['id']."\n";
			}
		} else {
				echo __("No result");
		}
		exit;
	}
	
	/*
	 * for showing events posted by logged in user
	 */
	function my()
	{
		if(isset($this->params['isAjax']) && $this->params['isAjax'] == 1)
		{
			Configure::write('debug',0);
		}
		$loggedInUserId = $this->Session->read('Auth.User.id');
		$conditions = array("Event.user_id" => $loggedInUserId);
		$this->Event->setScope('published');
		$this->paginate['recursive'] = 0;
		$this->paginate['limit'] = 10;
		$order = array("Event.created" => "DESC");
		$this->paginate['order'] = $order;
		if(!isset($this->paginate['conditions']))
		{
			$this->paginate['conditions'] = array();
		}
		$this->paginate['conditions'] = am($this->paginate['conditions'], $conditions);
		$events = $this->paginate();
		$this->pageTitle = __("My Posted Events");
		$view_type = 'blog_view';
		$this->set('view_type', $view_type);
		$this->set('categories',$this->Event->EventCategory->find('list'));
		$this->set('events', $events);
		$this->set('loggedInUserId', $loggedInUserId);
	}
	
}
?>